# -*- coding: utf-8 -*-
import decimal
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'https://ebank.xfuoo.com/payment/v1/order/'
_QUERY_GATEWAY = 'https://ebank.xfuoo.com/payment/v1/order/{}-{}?merchantId={}&charset=utf-8&orderNo={}&signType=SHA&sign={}'

APP_CONF = {
    '100000000002488': {
        'API_KEY': '4cacbg24c4f8a0117998e395gg5e6e7egc4804ed268ab03c1c0fe16c4af90cbe',
        'gateway': 'https://ebank.xfuoo.com/payment/v1/order/',
        'query_gateway': 'https://ebank.xfuoo.com/payment/v1/order/{}-{}?merchantId={}&charset=utf-8&orderNo={}&signType=SHA&sign={}',
    },
    '100000000003228': {  # QQ 京东 银联 loki
        'API_KEY': 'va0q5jrdi72nec8ctme11vvie3ms3wjkt53ze9h82vpnu5tgz1zcbk13vmow4f4p',
        'gateway': 'https://ebank.ztpo.cn/payment/v1/order/',
        'query_gateway': 'https://ebank.ztpo.cn/payment/v1/order/{}-{}?merchantId={}&charset=utf-8&orderNo={}&signType=SHA&sign={}',
    },
    '100000000003758': {  # 支付宝 loki
        'API_KEY': '4pselop8t1sn7z4u8r9st5ejwcsnyh6w1cljhr2f1ia5s1pmaq07hpy044rm3o1w',
        'gateway': 'https://ebank.xfuoo.com/payment/v1/order/',
        'query_gateway': 'https://ebank.xfuoo.com/payment/v1/order/{}-{}?merchantId={}&charset=utf-8&orderNo={}&signType=SHA&sign={}',
    },
    '100000000004371': {  # 支付宝 witch 11~5000
        'API_KEY': 'pqamli3lb2lffe95adql3a14mn4f1z8zbh8zdrnvfnu6hfk6o8udirj0hz9yzk7e',
        'gateway': 'https://ebank.xfuoo.com/payment/v1/order/',
        'query_gateway': 'https://ebank.xfuoo.com/payment/v1/order/{}-{}?merchantId={}&charset=utf-8&orderNo={}&signType=SHA&sign={}',
    },
    '100000000004373': {  # 支付宝 loki 11~5000
        'API_KEY': 'y7vfehz2ho2o58qj697hx1vubqbe2tyrn26pyga5fa48hgzo8jptrj8tdrf2n804',
        'gateway': 'https://ebank.xfuoo.com/payment/v1/order/',
        'query_gateway': 'https://ebank.xfuoo.com/payment/v1/order/{}-{}?merchantId={}&charset=utf-8&orderNo={}&signType=SHA&sign={}',
    },
    '100000000004370': {  # 支付宝 dwc 11~5000
        'API_KEY': 'dx8suh6vlou5mvlozstmfjp99jc3mgrx65a0g8jg0lauyp90nnnj7lgczqkjc71u',
        'gateway': 'https://ebank.xfuoo.com/payment/v1/order/',
        'query_gateway': 'https://ebank.xfuoo.com/payment/v1/order/{}-{}?merchantId={}&charset=utf-8&orderNo={}&signType=SHA&sign={}',
    },
    '100000000004372': {  # 支付宝 zs 11~5000
        'API_KEY': 'myeum0pc0jnr1pikjzk9j52gbrnxsryfsdzkhssgyy1xs6fdlixvpai71h25tjom',
        'gateway': 'https://ebank.xfuoo.com/payment/v1/order/',
        'query_gateway': 'https://ebank.xfuoo.com/payment/v1/order/{}-{}?merchantId={}&charset=utf-8&orderNo={}&signType=SHA&sign={}',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s = s[:len(s) - 1]
    s += key
    print s
    m = hashlib.sha1()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('signType')
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("xftpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    orderid = str(pay.id)

    if service == 'alipay':
        payment = 'ALIPAY'
    elif service == 'wechat':
        payment = 'WXPAY'
    elif service == 'qq':
        payment = 'QQPAY'
    elif service == 'jd':
        payment = 'JDPAY'
    elif service == 'quick':
        payment = 'QUICKPAY'
    else:
        payment = 'QQPAY'

    parameter_dict = OrderedDict((
        ('service', 'online_pay'),
        ('paymentType', '1'),
        ('merchantId', app_id),
        ('returnUrl', '{}/pay/api/{}/xftpay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('notifyUrl', '{}/pay/api/{}/xftpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('orderNo', orderid),
        ('title', 'goods'),
        ('body', 'goods'),
        ('totalFee', decimal.Decimal(pay_amount).quantize(decimal.Decimal('0.00'))),
        ('buyerEmail', '4026739782@qq.com'),
        ('paymethod', 'directPay'),
        ('defaultbank', payment),
        ('isApp', 'app'),
        ('backUrl', '{}/pay/api/{}/xftpay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('charset', 'UTF-8'),
    ))

    if payment == 'QUICKPAY':
        parameter_dict['paymethod'] = 'bankPay'
        parameter_dict['isApp'] = 'web'

    if payment == 'ALIPAY':
        parameter_dict['isApp'] = 'H5'

    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    parameter_dict['signType'] = 'SHA'
    gateway = _get_gateway(app_id) + '%s-%s' % (app_id, orderid)
    _LOGGER.info("xftpay create  data: %s, %s", parameter_dict, gateway)

    if payment == 'QUICKPAY' or payment == 'ALIPAY':
        html_text = _build_form(parameter_dict, gateway)
        cache_id = redis_cache.save_html(pay.id, html_text)
        return {'charge_info': settings.PAY_CACHE_URL + cache_id}
    else:
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        response = requests.post(gateway, data=parameter_dict, headers=headers, timeout=60)
        _LOGGER.info("xftpay create rsp data: %s %s", response.status_code, response.text)
        j = json.loads(response.text)
        return {'charge_info': j[u'codeUrl']}


def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("xftpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['order_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('xftpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = data['trade_status']
    trade_no = data['trade_no']
    total_fee = float(data['total_fee'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == 'TRADE_FINISHED':
        _LOGGER.info('xftpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    order_id = str(pay_id)
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('charset', 'utf-8'),
        ('merchantId', app_id),
        ('orderNo', str(order_id)),
    ))
    parameter_dict['signData'] = generate_sign(parameter_dict, api_key)
    parameter_dict['signType'] = 'SHA'
    url = _get_query_gateway(app_id).format(app_id, order_id, app_id, order_id, parameter_dict['signData'])
    _LOGGER.info('xftpay query url :%s', url)
    response = requests.get(url)
    _LOGGER.info('xftpay query rsp :%s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = data['status']
        trade_no = data['tradeNo']
        total_fee = float(data['amount'])

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == 'completed':
            _LOGGER.info('xftpay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
            print("order process successfully. %s" % pay_order.id)
    else:
        _LOGGER.warn('xftpay data error, status_code: %s', response.status_code)
